<template>
    <van-nav-bar title="收货地址" left-text="" left-arrow @click-left="goBack" />
    <!-- 从订单 -->
    <van-address-list v-if="action" v-model="chosenAddressId" :list="list" default-tag-text="默认" @add="onAdd"
        @edit="onEdit" @select="choiced" />
    <!-- 个人中心 -->
    <van-address-list v-else v-model="chosenAddressId" :list="list" default-tag-text="默认" @add="onAdd" @edit="onEdit"
        @select="selected" />
</template>
<script setup>
const router = useRouter();
const route = useRoute();
const chosenAddressId = ref("");
const list = ref([]);
const { cookies } = useCookies();
const LoginUser = reactive(cookies.get("LoginUser") ?? {});
const action = ref(route.query.action ?? '')
const onAdd = () => {
    router.push("/business/address/add");
};
const goBack = () => {
    history.back();
};
const onEdit = (val) => {
    router.push({
        path: "/business/address/edit",
        query: {
            addressid: val.id,
        },
    });
};
onBeforeMount(() => {
    getAddressData();
});
const getAddressData = async () => {
    let result = await Api.addressIndex({
        busid: LoginUser.id,
    });
    if (result.code == 1) {
        list.value = [];
        result.data.forEach((item) => {
            list.value.push({
                id: item.id,
                name: item.consignee,
                tel: item.mobile,
                address: item.region_text,
                isDefault: item.status == "1" ? true : false
            });
            if (item.status == "1") {
                chosenAddressId.value = item.id;
            }
        });
    } else {
        showFailToast(result.msg);
    }
};
// 切换默认地址
const selected = async (val) => {
    let result = await Api.addressCheck({
        busid: LoginUser.id,
        addressid: val.id,
    });
    if (result.code == 1) {
        getAddressData();
    } else {
        showFailToast(result.msg);
    }
};

const choiced = (val) => {
    cookies.set("Address", {
        id: val.id,
        consignee: val.name,
        mobile: val.tel
    });
    goBack()
}
</script>
<style>
.van-tag--round{
    background: #32806f
}
.van-button--primary{
    background: #32806f;
    border:#32806f
}
</style>